package salesmenService

import (
	"encoding/json"
	"errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"hc_server/pkg/gredis"
	"hc_server/routers/models"
	"hc_server/routers/service/cache_service"
)

type Salesmen struct {
	Id            int
	Name          string
	Mobile        interface{}
	AgentId       string
	AgentRelation string

	PageNum  int
	PageSize int
	Keyword  string
}

// SalesmenExistByID 销售员是否存在
func (s *Salesmen) SalesmenExistByID() error {
	return models.SalesmenExistByID(s.Id)
}

// SalesmenExistByMobile 销售员是否存在
func (s *Salesmen) SalesmenExistByMobile() error {
	return models.SalesmenExistByMobile(cast.ToString(s.Mobile))
}

// SalesmenRegister 添加销售员
func (s *Salesmen) SalesmenRegister() error {
	err := models.SalesmenExistByMobile(cast.ToString(s.Mobile))
	if err == nil {
		return errors.New("该手机号已存在")
	}
	agt, err := models.AgentRelationGetInfoByAgentNo(s.AgentId)
	if err != nil {
		return err
	}
	return models.SalesmenRegister(models.Salesmen{
		Name:          s.Name,
		Mobile:        cast.ToString(s.Mobile),
		AgentId:       s.AgentId,
		AgentRelation: agt["relation"],
	})
}

// SalesmenMerchantSalesmenList 获取业务员列表
func (s *Salesmen) SalesmenMerchantSalesmenList() (map[string]interface{}, error) {
	var (
		result, cacheResult map[string]interface{}
	)

	//redis获取数据
	cache := cache_service.Salesmen{
		ID:       s.Id,
		PageNum:  s.PageNum,
		PageSize: s.PageSize,
		Keyword:  s.Keyword,
	}
	key := cache.GetSalesmenKey()
	if gredis.Exists(key) {
		data, err := gredis.Get(key)
		if err != nil {
			logrus.WithError(err).Errorf("获取业务员列表失败:key:%s,err:%v", key, err)
			return nil, errors.New("获取业务员列表失败")
		} else {
			json.Unmarshal(data, &cacheResult)
			return cacheResult, nil
		}
	}

	//数据库获取数据
	result, err := models.SalesmenMerchantSalesmenList(s.Id, s.PageNum, s.PageSize, s.Keyword)
	if err != nil {
		return nil, err
	}

	gredis.Set(key, result, 3600)
	return result, nil
}
